package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.util.LoginFlowManager;
import com.pansoft.openplanet.widget.SelectAvatarDialog;

import java.io.File;

import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 设置头像
 * Created by will on 18-3-20.
 */

public class SetupAvatarActivity extends TCBaseActivity implements View.OnClickListener {

    private ImageView ivAvatar;
    int userId;
    private String number, userName;
    private String pictureUrlPath;//头像在网络上的位置
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
    private SelectAvatarDialog selectAvatarDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        pictureAndCropManager = new PictureAndCropManager(this);
        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);
        setContentView(R.layout.talk_chain_activity_set_avatar);
        number = getIntent().getExtras().getString("number");
        userName = getIntent().getExtras().getString("userName");
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvName = (TextView) findViewById(R.id.tv_nickname);
        if (userName == null) {
            tvName.setText(R.string.openplanet_user);
        } else {
            tvName.setText(userName);
        }
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.common_set_avatar);
        TextView tvSkip = (TextView) findViewById(R.id.tv_save);
        tvSkip.setVisibility(View.VISIBLE);
        ivAvatar = (ImageView) findViewById(R.id.wallet_top);
        ivAvatar.setOnClickListener(this);
        tvSkip.setText(R.string.common_text_skip);
        tvSkip.setOnClickListener(this);
        Button tvNext = (Button) findViewById(R.id.tv_set_avatar);
        tvNext.setOnClickListener(this);

        EnvironmentVariable.setProperty(LoginFlowManager.getIsUpdateAvatarKey(number),"true");
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_set_avatar) {
            if (pictureUrlPath == null) {
                ToastUtil.showToast(getApplicationContext(), R.string.common_text_please_choose_pic);
                return;
            }
            showLoading(R.string.common_text_setavataring);
            GetHttpUtil.updateMyselfInfo(SetupAvatarActivity.this,
                    "avatar", pictureUrlPath, new GetHttpUtil
                            .UpdateUserInfoCallBack() {
                        @Override
                        public void updateSuccess(boolean isSuccess) {
                            if (isSuccess) {
                                dismissLoading();
                                //设置完成
                                EnvironmentVariable.setProperty(LoginFlowManager.getIsUpdateAvatarKey(number),"false");
                                ToastUtil
                                        .showToast(getApplicationContext(), R.string.common_text_set_avatar_success);
                                Intent intent = new Intent(SetupAvatarActivity.this, ImportFansActivity.class);
                                intent.putExtra("number", number);
                                startActivity(intent);

                            } else {
                                dismissLoading();
                                ToastUtil
                                        .showToast(getApplicationContext(), R.string.common_text_set_avatar_fail);
                            }

                        }
                    });

        } else if (id == R.id.tv_save) {
            //取消设置头像  设置头像流程完成
            EnvironmentVariable.setProperty(LoginFlowManager.getIsUpdateAvatarKey(number),"false");
            Intent intent = new Intent(this, ImportFansActivity.class);
            intent.putExtra("number", number);
            startActivity(intent);
        } else if (id == R.id.wallet_top) {
            selectAvatarDialog.show();
        }
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission() && selectAvatarDialog!=null) {
            selectAvatarDialog.startTakePhoto();
        }
    }
    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(Uri.fromFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null)
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    break;

                case PHOTO_REQUEST_CUT:
                    Log.i("剪裁后头像文件路径：", pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtil
                                .showToast(getApplicationContext(), R.string.common_text_network_error);
                        return;
                    }
                    showLoading(R.string.common_text_uploading);

                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                dismissLoading();
                                if (isSuccess) {
                                    Log.i("MyUserInfoActivity", "---头像在云盘服务器上的路径:" + url);
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    ToastUtil.showToast(getApplicationContext(), R.string.common_text_upload_success);
                                    showUserAvatar(pictureUrlPath);
                                } else {
                                    ToastUtil.showToast(getApplicationContext(), R.string.common_text_upload_fail_again);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                    }

                    break;

                default:
                    break;

            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    private void showUserAvatar(String url) {
        RequestOptions options = new RequestOptions()
                .circleCrop().error(R.drawable.avatar_default_image).placeholder(R.drawable.avatar_default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(this)
                .load(url)
                .apply(options)
                .into(ivAvatar);
    }
}
